using System.Collections.Generic;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace ShuttleBus.Transports.AmazonSqs.Clients
{
    public class SqsWrapper : ISqsClient
    {
        private readonly AmazonSQS _sqs;
        private readonly IDictionary<string, string> _queues;

        public SqsWrapper(AmazonSQS sqs)
        {
            _sqs = sqs;
            _queues = new Dictionary<string, string>();
        }

        public string GetQueueArn(string queueName)
        {
            if (!_queues.ContainsKey(queueName))
            {
                var request = new CreateQueueRequest { QueueName = queueName };
                var response = _sqs.CreateQueue(request);
                var queueUrl = response.CreateQueueResult.QueueUrl;

                var attributesRequest = new SetQueueAttributesRequest()
                    .WithQueueUrl(queueUrl)
                    .WithAttribute(new Attribute() {Name = "MaximumMessageSize", Value = "65536"});

                _sqs.SetQueueAttributes(attributesRequest);

                var getQueueAttributeRequest = new GetQueueAttributesRequest()
                    .WithAttributeName("QueueArn")
                    .WithQueueUrl(queueUrl);

                var attributeResponse = _sqs.GetQueueAttributes(getQueueAttributeRequest);

                _queues[queueName] = attributeResponse.GetQueueAttributesResult.Attribute[0].Value;

            }
            return _queues[queueName];
        }
    }
}